<template>
  <div class="container">
    <el-row class="header">
      <el-col class="asd" :span="14" align="left">
        <el-input
          clearable
          v-model="data.params.projectName"
          placeholder="项目名称/编号/合同名称/合同编号"
          style="width: 300px; margin-right: 15px"
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col class="asd" :span="10" align="right">
        <el-button v-limit="'XMZX:HTGL:HTBG:EXPORT'" class="ordinary" @click="handleExport()"
          >批量导出</el-button
        >
        <el-button v-limit="'XMZX:HTGL:HTBG:DELETE'" type="danger" @click="handleDel()"
          >移除</el-button
        >
        <el-button v-limit="'XMZX:HTGL:HTBG:APPLY'" type="primary" @click="handleChange()"
          >合同变更申请</el-button
        >
      </el-col>
    </el-row>
    <Table
      :hasOperate="false"
      :loading="data.isLoading"
      :table-arr="data.allTableData"
      :columns="data.columns"
      :page-size="data.params.size"
      :page-num="data.params.current"
      @selectList="getCurrentList"
      @row-click="handleRowClick"
    >
      <template #status>
        <el-table-column label="状态" width="100">
          <template #default="{ row }" class="status">
            <span class="draft" v-if="row.status == 0">草稿</span>
            <span class="pending" v-if="row.status == 1">待审批</span>
            <span class="approved" v-if="row.status == 2">正常办结</span>
            <span class="rejection" v-if="row.status == 3">已退回</span>
            <span class="rejection" v-if="row.status == 4">已撤办</span>
            <span class="rejection" v-if="row.status == 5">强制办结</span>
            <span class="rejection" v-if="row.status == 6">已废弃</span>
            <span class="rejection" v-if="row.status == 7">已挂起</span>
            <span class="rejection" v-if="row.status == 8">已驳回</span>
          </template>
        </el-table-column>
      </template>
      <template #operate="{ row }">
        <el-button
          v-limit="'XMZX:HTGL:HTBG:EDIT'"
          :disabled="row.status != 0"
          class="ordinary"
          @click="handleEdit(row)"
          >编辑</el-button
        >
        <el-button v-limit="'XMZX:HTGL:HTBG:DETAIL'" class="ordinary" @click="handleDetail(row)"
          >详情</el-button
        >
        <el-button
          v-if="row.status == 1 && row.currUserId?.split(',').includes(data.username)"
          v-limit="'XMZX:HTGL:HTBG:EXAMINE'"
          class="examine"
          @click="handleExamine(row)"
          >审批</el-button
        >
      </template>
    </Table>
    <div class="example-pagination-block">
      <el-pagination
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="data.total"
        :page-size="data.params.size"
        v-model:current-page="data.params.current"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 合同变更申请表格 -->
    <el-dialog
      v-model="data.changeDialog"
      width="60%"
      top="10vh"
      :title="data.currentHandle"
      @close="handleClose"
    >
      <el-tabs v-model="activeName" class="demo-tabs box">
        <el-tab-pane label="基本信息" name="1">
          <change v-if="data.changeDialog" :title="data.currentHandle" ref="changeForm"></change>
          <!-- <examine v-if="data.changeDialog"></examine> -->
        </el-tab-pane>
        <el-tab-pane
          label="流程图"
          name="2"
          v-if="
            (data.currentHandle == '合同变更审批' || data.currentHandle == '合同变更详情') &&
            data.currentRow.status != 0
          "
        >
          <flowChart
            v-if="data.changeDialog"
            :processInstanceId="data.processInstanceId"
          ></flowChart>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer" style="float: left" v-if="data.currentHandle == '合同变更审批'">
          <el-form label-width="120px" :rules="rules" ref="ruleFormRef" :model="ruleForm">
            <el-form-item label="审批意见" prop="comment">
              <el-input
                type="textarea"
                placeholder="审批意见"
                v-model="ruleForm.comment"
                style="width: 450px; margin-top: -10px"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>
        <span class="dialog-footer">
          <el-button @click="data.changeDialog = false">关闭</el-button>
          <el-button
            v-if="data.currentHandle == '合同变更申请' || data.currentHandle == '合同变更编辑'"
            type="primary"
            @click="handleSaveChange()"
            >保存</el-button
          >
          <el-button
            v-if="data.currentHandle == '合同变更申请' || data.currentHandle == '合同变更编辑'"
            type="primary"
            @click="handleSubmitChange()"
            >提交</el-button
          >
          <el-button
            v-if="data.currentHandle == '合同变更审批'"
            type="danger"
            @click="handleNoPass()"
            >审批驳回</el-button
          >
          <el-button
            v-if="data.currentHandle == '合同变更审批'"
            type="primary"
            @click="handlePass()"
            >审批通过</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 导出字段选择 -->
    <Export
      :detailList="data.detailList"
      :showing="data.exportDialog"
      @close="closeExport"
      @handle-filed="handleFiled"
    ></Export>
    <el-dialog
      v-model="data.dealVisible"
      title="系统正在处理中....."
      width="40%"
      top="14%"
      height="400"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-alert
        type="success"
        :closable="false"
        style="margin-bottom: 20px"
        description="当前流程正在处理中,请稍等……"
      >
      </el-alert>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import tableData from './tableHeader.json'
import {
  getChangeList,
  getDetailById,
  delBatchChange,
  exportContractChangeList,
  changeContractSubmit,
} from '../../api/contract'
import Export from '@/views/project/components/Export/index.vue'
import Table from '../../components/table2/table.vue'
import change from './components/change.vue'
import flowChart from '@/components/PublicProcess/Chart/flowChart.vue'

import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { changeContractSave } from '../../api/contract'
import { servicesLoading } from '@/utils/loading'
import { startProcess, allowProcess, refuseProcess } from '../../api/commom'
import { getProjectList } from '@/views/project/api/commom'

export default {
  components: {
    Table,
    change,
    flowChart,
    Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    let data = reactive({
      defaultExpandedKeys: [],
      tableTreeData: [],
      currentHandle: '合同变更申请',
      params: {
        projectName: '',
        current: 1,
        size: 10,
      },
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      currentList: [] as any,
      total: 0,
      ids: [],
      processInstanceId: '',
      changeDialog: false,
      dealVisible: false,
      examineDialog: false,
      currentRow: {} as any,
      exportDialog: false,
      detailList: [] as any,
      username: JSON.parse(localStorage.getItem('userInfo') as any).username,
    })
    const changeForm = ref()
    const ruleFormRef = ref()
    const ruleForm = reactive({
      comment: '',
    })
    const rules = reactive({
      comment: [{ required: true, message: '请输入审批意见', trigger: 'change' }],
    })
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      onSearch()
    }
    getProjectList().then((res) => {
      store.state.projectCenter.projectList = res.data.data
    })
    const onSearch = async () => {
      data.isLoading = true
      getChangeList(data.params).then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data
          result.records.map((item) => {
            item.signingDate = item.signingDate?.slice(0, 10)
          })
          data.allTableData = result.records
          data.total = result.total
          data.isLoading = false
        }
      })
    }
    onSearch()

    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }

    const defaultProps = {
      children: 'children',
      label: 'label',
    }
    const orgSearch = () => {
      data.params.current = 1
      console.log(data.params)
      onSearch()
    }
    const search = () => {
      data.params.current = 1
      onSearch()
    }
    const handleChange = () => {
      data.currentHandle = '合同变更申请'
      data.changeDialog = true
    }
    let changeContractForm = reactive(store.state.projectCenter.changeContractForm)
    const handleEdit = (row) => {
      data.currentRow = row
      const loading = servicesLoading({ fullscreen: false })
      getDetailById({
        id: row.id,
      }).then((res) => {
        loading.close()
        const resData = res.data.data
        console.log(resData, 'resData')
        for (let key in changeContractForm) {
          changeContractForm[key] = resData[key]
        }
        data.currentHandle = '合同变更编辑'
        data.changeDialog = true
      })
    }
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      data.currentRow = row
      const loading = servicesLoading({ fullscreen: false })
      getDetailById({
        id: row.id,
      }).then((res) => {
        // loading.close()
        // const resData = res.data.data
        // console.log(resData, 'resData')
        // for (let key in changeContractForm) {
        //   changeContractForm[key] = resData[key]
        // }
        // data.currentHandle = '合同变更详情'
        // data.changeDialog = true
        const resData = res.data.data
        console.log(resData, 'resData')
        data.processInstanceId = resData.processInstanceId
        for (let key in changeContractForm) {
          changeContractForm[key] = resData[key]
        }
        data.currentHandle = '合同变更详情'
        data.changeDialog = true
        loading.close()
      })
    }
    const handleDel = () => {
      if (data.ids.length) {
        let flag = true
        console.log(data.currentList, 'currentList')
        data.currentList.forEach((obj) => {
          if (obj.status != '0') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '仅能删除草稿状态的的变更申请',
            type: 'warning',
          })
          return
        }
        ElMessageBox.confirm('您确认删除所选中记录吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              delBatchChange(data.ids).then((res) => {
                console.log(res)
                onSearch()
                ElMessage({
                  message: '操作成功',
                  type: 'success',
                })
              })
            }
          },
        })
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          exportContractChangeList({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'contractName', title: '合同名称' },
        { fieldName: 'contractNumber', title: '合同编号' },
        { fieldName: 'projectLeaderName', title: '项目负责人' },
        { fieldName: 'projectUndertakingUnitName', title: '项目承担单位' },
        { fieldName: 'signingDate', title: '签订日期' },
        { fieldName: 'changeTypeName', title: '变更类型' },
        { fieldName: 'changeReason', title: '变更原因' },
      ]
    }
    // const handleExport = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     console.log('批量导出')
    //     exportContractChangeList({ ...data.params, ids: data.ids })
    //   })
    // }
    const handleSave = () => {
      data.changeDialog = false
    }
    const handleExamine = (row) => {
      data.currentRow = row
      const loading = servicesLoading({ fullscreen: false })
      //获取对应流程processInstanceId,渲染流程图
      getDetailById({
        id: row.id,
      }).then((res) => {
        const resData = res.data.data
        console.log(resData, 'resData')
        data.processInstanceId = resData.processInstanceId
        for (let key in changeContractForm) {
          changeContractForm[key] = resData[key]
        }
        data.currentHandle = '合同变更审批'
        data.changeDialog = true
        loading.close()
      })
    }
    // 处理不通过,提交的过程中.......
    let deal = (id, state) => {
      let times = setInterval(() => {
        getDetailById({
          id: id,
        }).then((res) => {
          const resData = res.data.data
          if (resData.status == state || (state == 2 && resData.status == 1)) {
            data.dealVisible = false
            onSearch()
            ElMessage({
              message: '流程办理成功',
              type: 'success',
            })
            clearTimeout(times)
          }
        })
      }, 3000)
    }
    //保存变更申请
    const handleSaveChange = () => {
      changeForm.value.submitForm().then(() => {
        if (data.currentHandle == '合同变更申请') {
          changeContractSave({
            ...changeContractForm,
          }).then((res) => {
            if (res.data.code == 200) {
              ElMessage({
                message: '保存成功',
                type: 'success',
              })
              data.changeDialog = false
              onSearch()
            }
          })
        } else if (data.currentHandle == '合同变更编辑') {
          changeContractSubmit({
            ...changeContractForm,
          }).then((res) => {
            if (res.data.code == 200) {
              ElMessage({
                message: '保存成功',
                type: 'success',
              })
              data.changeDialog = false
              onSearch()
            }
          })
        }
      })
    }
    //提交变更申请流程
    const handleSubmitChange = () => {
      ElMessageBox.confirm('确认提交该合同变更申请吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        data.changeDialog = false
        const loading = servicesLoading({ fullscreen: true })
        if (data.currentHandle == '合同变更申请') {
          changeContractSave({
            ...changeContractForm,
          }).then((res) => {
            if (res.data.code == 200) {
              ElMessage({
                message: '保存成功',
                type: 'success',
              })
              let businessKey = res.data.data
              startProcess({
                flowKey: 'change-contract',
                businessKey: businessKey,
                businessType: 'YW19',
                random: new Date().valueOf(),
              }).then((res) => {
                loading.close()
                if (res.data.code != 200) {
                  ElMessage({
                    message: '流程启动失败,请稍后重试',
                    type: 'warning',
                  })
                } else {
                  data.dealVisible = true
                  deal(businessKey, 1)
                }
              })
            }
          })
        } else if (data.currentHandle == '合同变更编辑') {
          startProcess({
            flowKey: 'change-contract',
            businessKey: data.currentRow.id,
            businessType: 'YW19',
            random: new Date().valueOf(),
          }).then((res) => {
            loading.close()
            if (res.data.code != 200) {
              ElMessage({
                message: '流程启动失败,请稍后重试',
                type: 'warning',
              })
            } else {
              data.dealVisible = true
              deal(data.currentRow.id, 1)
            }
          })
        }
      })
    }
    //审批通过
    const handlePass = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('确认通过本次申请吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            handleResult(allowProcess, 2)
          })
        }
      })
    }
    const handleNoPass = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('确认驳回本次申请吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            handleResult(refuseProcess, 8)
          })
        }
      })
    }
    const handleResult = (handleProcess, status) => {
      const loading = servicesLoading({ fullscreen: true, text: '正在请求流程' })
      handleProcess({
        procInsId: data.processInstanceId,
        comment: ruleForm.comment,
        flowKey: 'change-contract',
        businessKey: data.currentRow.id,
        businessType: 'YW19',
        random: new Date().valueOf(),
      })
        .then((res) => {
          loading.close()
          if (res.data.code != 200) {
            ElMessage({
              message: res.data.message,
              type: 'warning',
            })
          } else {
            data.changeDialog = false
            data.dealVisible = true
            deal(data.currentRow.id, status)
          }
        })
        .catch(() => {
          loading.close()
        })
    }
    const handleClose = () => {
      console.log('对话框关闭了')
      data.changeDialog = false
      activeName.value = '1'
      if (data.currentHandle == '合同变更审批') {
        ruleFormRef.value.resetFields()
      }
    }
    return {
      store,
      data,
      rules,
      ruleForm,
      ruleFormRef,
      changeForm,
      activeName,
      defaultProps,
      getCurrentList,
      onSearch,
      handleCurrentChange,
      handleSizeChange,
      handleEdit,
      handleDetail,
      handleRowClick,
      handleDel,
      handleChange,
      handleSaveChange,
      handleSubmitChange,
      handleExamine,
      handleSave,
      handleClose,
      closeExport,
      handleFiled,
      handleExport,
      orgSearch,
      search,
      handlePass,
      handleNoPass,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  // padding: 0 20px 20px;
  padding: 20px;
}
.examine {
  color: aliceblue;
  background-color: #408059;
}
.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/deep/.demo-tabs > .el-tabs__content {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}
// .box {
//   :deep(.el-tabs__content) {
//     max-height: 200px;
//     overflow-y: auto;
//   }
// }

/deep/.demo-tabs > .el-tabs__content::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
:deep(.el-dialog__body) {
  display: block;
  padding: 10px 20px;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid rgb(234, 230, 230);
}
// :deep(.el-dialog__footer){
//   height: 80px;
// }
</style>
